package com.example.androidcomplete02.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.example.androidcomplete02.R;

public class WebService extends Activity implements OnClickListener {
	TextView tv;
	ProgressDialog progressDlg;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch28_webservice);
		findViewById(R.id.reqbtn).setOnClickListener(this);
		tv = (TextView) findViewById(R.id.result);
	}

	public void onClick(View v) {
		String str = "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=2723052600";
		new HttpRequestTask().execute(str);
	}

	private class HttpRequestTask extends AsyncTask<String, Void, String> {
		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(WebService.this, "Wait",
					"Downloading...");
		}

		protected void onPostExecute(String result) {
			progressDlg.dismiss();
			tv.setText(result);
		}

		protected String doInBackground(String... strs) {
			StringBuffer sb = new StringBuffer();
			BufferedReader br = null;
			HttpURLConnection con = null;
			String line = null;
			try {
				URL url = new URL(strs[0]);
				con = (HttpURLConnection) url.openConnection();
				if (con != null) {
					if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
						br = new BufferedReader(new InputStreamReader(
								con.getInputStream()));
					}
				}
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					br.close();
					con.disconnect();
				} catch (Exception e) {
				}
			}
			return sb.toString();
		}
	}// end of class HttpRequestTask
}// end of class WebService